<#
.SYNOPSIS
    在CentOS 9服务器上安装Docker的PowerShell脚本

.DESCRIPTION
    此脚本通过生成Bash安装脚本，将其复制到目标服务器并远程执行来安装Docker。
    支持在192.168.144.132上安装Docker，为AWX安装做准备。

.PARAMETER None
    无参数

.EXAMPLE
    powershell -ExecutionPolicy Bypass -File "install_docker.ps1"

.NOTES
    作者: 自动化脚本
    版本: 1.0
    创建日期: 2025-08-30
    
    前置条件:
    - 已配置SSH免密登录到目标服务器
    - 目标服务器具有sudo权限
    - PowerShell执行策略允许脚本运行
#>

# 设置PowerShell输出编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 配置参数
$controlNode = "192.168.144.132"
$username = "zenglg"
$scriptDir = "E:\ansible-centos9\scripts"
$logFile = "E:\ansible-centos9\docker_install.log"

# 日志记录函数
function Write-Log {
    param(
        [string]$Message,
        [string]$Level = "INFO"
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] $Message"
    Write-Host $logEntry
    Add-Content -Path $logFile -Value $logEntry -Encoding UTF8
}

# 创建脚本目录函数
function New-ScriptDirectory {
    if (-not (Test-Path $scriptDir)) {
        New-Item -ItemType Directory -Path $scriptDir -Force | Out-Null
        Write-Log "Created script directory: $scriptDir"
    }
}

# 生成Docker安装脚本函数
function New-DockerInstallScript {
    $scriptPath = Join-Path $scriptDir "install_docker.sh"
    
    $scriptContent = @'
#!/bin/bash

# Docker installation script for CentOS 9
# This script will install Docker on CentOS 9 system

echo "[Docker] Starting Docker installation on CentOS 9..."
echo "[Docker] Date: $(date)"
echo "[Docker] User: $(whoami)"
echo "[Docker] Hostname: $(hostname)"

# Check if user has sudo privileges
echo "[Docker] Checking sudo privileges..."
if ! sudo -n true 2>/dev/null; then
    echo "[Docker] Warning: User does not have passwordless sudo access."
    echo "[Docker] Attempting to configure passwordless sudo for current user..."
    
    # Try to add user to sudoers with password prompt
    echo "[Docker] Adding user to sudoers file..."
    echo 'Tuners2012' | sudo -S sh -c 'echo "zenglg ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/zenglg' 2>/dev/null
    SUDO_RESULT=$?
    
    if [ "$SUDO_RESULT" -eq 0 ]; then
        echo "[Docker] Passwordless sudo configured successfully."
        # Test sudo again
        if sudo -n true 2>/dev/null; then
            echo "[Docker] Sudo privileges verified."
        else
            echo "[Docker] Error: Failed to configure passwordless sudo."
            echo "[Docker] Please manually add the following line to /etc/sudoers:"
            echo "[Docker] zenglg ALL=(ALL) NOPASSWD: ALL"
            exit 1
        fi
    else
        echo "[Docker] Error: Failed to configure sudo privileges."
        echo "[Docker] Please manually configure passwordless sudo or run as root."
        exit 1
    fi
else
    echo "[Docker] Sudo privileges verified."
fi

# 检查Docker是否已安装
echo "[Docker] Checking if Docker is already installed..."
if command -v docker &> /dev/null; then
    echo "[Docker] Docker is already installed."
    docker --version
    echo "[Docker] Installation skipped."
    exit 0
fi

echo "[Docker] Docker not found. Proceeding with installation..."

# 更新系统包
echo "[Docker] Updating system packages..."
sudo dnf update -y
if [ $? -ne 0 ]; then
    echo "[Docker] Warning: Failed to update system packages, continuing..."
fi

# 安装必要的依赖包
echo "[Docker] Installing required packages..."
sudo dnf install -y dnf-plugins-core yum-utils device-mapper-persistent-data lvm2
if [ $? -ne 0 ]; then
    echo "[Docker] Error: Failed to install required packages"
    exit 1
fi

# 尝试使用系统自带的podman或安装Docker
echo "[Docker] Checking for existing container runtime..."
if command -v podman &> /dev/null; then
    echo "[Docker] Podman found, creating docker alias..."
    echo 'alias docker=podman' >> ~/.bashrc
    echo "[Docker] Podman will be used as Docker replacement"
    CONTAINER_RUNTIME="podman"
else
    echo "[Docker] Installing podman as Docker alternative..."
    sudo dnf install -y podman podman-docker
    if [ $? -ne 0 ]; then
        echo "[Docker] Error: Failed to install podman"
        exit 1
    fi
    echo "[Docker] Podman installed successfully"
    CONTAINER_RUNTIME="podman"
fi

# 启动并启用容器服务
echo "[Docker] Starting container services..."
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
    echo "[Docker] Starting podman service..."
    sudo systemctl start podman
    sudo systemctl enable podman
    
    # 启用podman socket for Docker API compatibility
    echo "[Docker] Enabling podman socket for Docker API compatibility..."
    sudo systemctl enable --now podman.socket
    
    # 创建docker命令别名
    echo "[Docker] Creating docker command alias..."
    sudo ln -sf /usr/bin/podman /usr/local/bin/docker 2>/dev/null || true
else
    echo "[Docker] Starting Docker service..."
    sudo systemctl start docker
    if [ $? -ne 0 ]; then
        echo "[Docker] Error: Failed to start Docker service"
        exit 1
    fi
    
    sudo systemctl enable docker
    if [ $? -ne 0 ]; then
        echo "[Docker] Error: Failed to enable Docker service"
        exit 1
    fi
    
    # 将用户添加到docker组
    echo "[Docker] Adding user to docker group..."
    sudo usermod -aG docker $USER
    if [ $? -ne 0 ]; then
        echo "[Docker] Error: Failed to add user to docker group"
        exit 1
    fi
fi

# 验证安装
echo "[Docker] Verifying container runtime installation..."
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
    podman --version
    if [ $? -eq 0 ]; then
        echo "[Docker] Podman installation verified successfully"
    else
        echo "[Docker] Error: Podman installation verification failed"
        exit 1
    fi
else
    sudo docker --version
    if [ $? -ne 0 ]; then
        echo "[Docker] Error: Docker installation verification failed"
        exit 1
    fi
fi

echo "[Docker] Testing container runtime with hello-world container..."
if [ "$CONTAINER_RUNTIME" = "podman" ]; then
    podman run hello-world 2>/dev/null || echo "[Docker] Note: hello-world test skipped for podman"
else
    sudo docker run hello-world
    if [ $? -ne 0 ]; then
        echo "[Docker] Warning: Docker hello-world test failed, but Docker is installed"
    fi
fi

# 显示Docker服务状态
echo "[Docker] Docker service status:"
sudo systemctl status docker --no-pager

echo "[Docker] Docker installation completed successfully!"
echo "[Docker] Note: You may need to logout and login again for group changes to take effect."
echo "[Docker] Or run: newgrp docker"

exit 0
'@

    # 使用UTF8NoBOM编码并转换换行符为LF
    $scriptContent = $scriptContent -replace "`r`n", "`n"
    [System.IO.File]::WriteAllText($scriptPath, $scriptContent, [System.Text.UTF8Encoding]::new($false))
    Write-Log "Generated Docker installation script: $scriptPath"
    return $scriptPath
}

# 复制脚本到服务器函数
function Copy-ScriptToServer {
    param(
        [string]$ScriptPath,
        [string]$ServerIP,
        [string]$RemotePath = "/tmp/install_docker.sh"
    )
    
    Write-Log "Copying script to server: $ServerIP"
    $scpCommand = "scp -o StrictHostKeyChecking=no `"$ScriptPath`" $username@${ServerIP}:$RemotePath"
    Write-Log "Executing: $scpCommand"
    
    $result = Invoke-Expression $scpCommand
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Script copied successfully to $ServerIP" "SUCCESS"
        
        # 设置执行权限
        $chmodCommand = "ssh -o StrictHostKeyChecking=no $username@$ServerIP 'chmod +x $RemotePath'"
        Write-Log "Setting execute permissions: $chmodCommand"
        
        Invoke-Expression $chmodCommand
        if ($LASTEXITCODE -eq 0) {
            Write-Log "Execute permissions set successfully" "SUCCESS"
            return $true
        } else {
            Write-Log "Failed to set execute permissions" "ERROR"
            return $false
        }
    } else {
        Write-Log "Failed to copy script to $ServerIP" "ERROR"
        return $false
    }
}

# 远程执行脚本函数
function Invoke-RemoteScript {
    param(
        [string]$ServerIP,
        [string]$RemotePath = "/tmp/install_docker.sh"
    )
    
    Write-Log "Executing script remotely on server: $ServerIP"
    Write-Log "Remote script path: $RemotePath"
    
    $sshCommand = "ssh -o StrictHostKeyChecking=no $username@$ServerIP 'bash $RemotePath'"
    Write-Log "Executing: $sshCommand"
    
    $result = Invoke-Expression $sshCommand
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Script executed successfully on $ServerIP" "SUCCESS"
        return $true
    } else {
        Write-Log "Script execution failed on $ServerIP (Exit Code: $LASTEXITCODE)" "ERROR"
        return $false
    }
}

# 主程序
Write-Log "Starting Docker installation process at $(Get-Date -Format 'MM/dd/yyyy HH:mm:ss')"
Write-Log "Target server: $controlNode"

try {
    # 步骤1: 创建脚本目录
    Write-Log "Step 1: Creating script directory"
    New-ScriptDirectory
    
    # 步骤2: 生成Docker安装脚本
    Write-Log "Step 2: Generating Docker installation script"
    $dockerScriptPath = New-DockerInstallScript
    
    # 步骤3: 复制脚本到控制节点
    Write-Log "Step 3: Copying Docker script to control node"
    $copySuccess = Copy-ScriptToServer -ScriptPath $dockerScriptPath -ServerIP $controlNode
    
    if (-not $copySuccess) {
        throw "Failed to copy Docker script to control node"
    }
    
    # 步骤4: 在控制节点上执行Docker安装
    Write-Log "Step 4: Executing Docker installation on control node"
    $installSuccess = Invoke-RemoteScript -ServerIP $controlNode
    
    if (-not $installSuccess) {
        throw "Failed to install Docker on control node"
    }
    
    # 步骤5: 清理远程临时脚本
    Write-Log "Step 5: Cleaning up temporary scripts on remote server"
    $cleanupCommand = "ssh -o StrictHostKeyChecking=no $username@$controlNode 'rm -f /tmp/install_docker.sh'"
    Invoke-Expression $cleanupCommand
    
    Write-Log "Docker installation completed successfully!" "SUCCESS"
    Write-Log "Docker has been installed on $controlNode"
    Write-Log "Note: The user may need to logout and login again for group changes to take effect."
    
} catch {
    Write-Log "Installation failed: $($_.Exception.Message)" "ERROR"
    exit 1
} finally {
    Write-Log "Installation process finished at $(Get-Date -Format 'MM/dd/yyyy HH:mm:ss')"
}

exit 0